package main

import (
	"bufio"
	"encoding/binary"
	"fmt"
	"io"
	"net"
	"os"
)

func main() {
	var g_conn net.Conn
	go func() {
		addr := "127.0.0.1:3000"
		conn, err := net.Dial("tcp", addr)
		if err != nil {
			fmt.Printf("connect fail, err = %v\n", err)
			os.Exit(0)
		}
		g_conn = conn
		for {
			var b [4]byte
			bufMsgLen := b[:4]
			if _, err := io.ReadFull(conn, bufMsgLen); err != nil {
				fmt.Printf("io.ReadFull1 fail, err = %v\n", err)
				return
			}
			msgLen := binary.LittleEndian.Uint32(bufMsgLen)
			leftLen := msgLen - 4

			if leftLen > 10240 {
				fmt.Printf("leftLen = %v\n", leftLen)
				return
			}

			tBuf := make([]byte, leftLen)
			if _, err := io.ReadFull(conn, tBuf); err != nil {
				fmt.Printf("io.ReadFull2 fail, err = %v\n", err)
				return
			}
			bufMsgID := tBuf[:2]
			msgID := binary.LittleEndian.Uint16(bufMsgID)
			bufMsgData := tBuf[2:]

			fmt.Printf("read msg id[%v]: %v\n", msgID, string(bufMsgData))
		}
	}()
	inputReader := bufio.NewReader(os.Stdin)
	for {
		fmt.Println("Please enter some input: ")
		input, err := inputReader.ReadString('\n')
		if err != nil {
			fmt.Printf("input fail, err = %v\n", err)
			os.Exit(0)
		}
		sendlen := len(input) + 6
		var sendbuf []byte = make([]byte, sendlen)
		bufMsgLen := sendbuf[:4]
		bufMsgID := sendbuf[4:6]
		binary.LittleEndian.PutUint32(bufMsgLen, uint32(sendlen))
		binary.LittleEndian.PutUint16(bufMsgID, 123)
		copy(sendbuf[6:], input)

		_, err = g_conn.Write(sendbuf)
		if err != nil {
			fmt.Printf("send msg fail, err = %v\n", err)
			os.Exit(0)
		}
	}
}
